package cc.ufinity.networkdiagnose.widget;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.APInfo;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TaskDetailWidget extends GeneralTestWidget {

    private Task task;
    private Handler handler;
    private WlanManager wlanManager;
    private TelManager tm;
    private LinearLayout detailLayout;
    private Button btnBack;
    private Activity ctx;
    private Task_Test_Widget ttw;
    private ListView wifiView;
    private EditText taskAddressText;
    private boolean updated = false;
    private boolean connecting;
    private List<APInfo> info;
    private LinearLayout taskBtnLayout;

    public TaskDetailWidget(Activity context) {
        super(context);
        inflate(context, R.layout.task_detail_widget, this);
        ctx = context;
        detailLayout = (LinearLayout) this.findViewById(R.id.task_detail_layout);
        taskBtnLayout = (LinearLayout) this.findViewById(R.id.task_btn_layout);
        btnBack = (Button) this.findViewById(R.id.task_btnback);
        wifiView = (ListView) this.findViewById(R.id.taskWifiListView);
        taskAddressText = (EditText) this.findViewById(R.id.taskAddressText);
        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TaskWidget tw = new TaskWidget(ctx);
                ctx.setContentView(tw);
                tw.start();    //刷新列表////////////////////////////////////////////////////////////////////
            }
        });
        wifiView.setOnItemClickListener(new OnItemClickListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> r = (Map<String, Object>) wifiView.getAdapter().getItem(position);
                selectedScanResult = (ScanResult) r.get("scan");
                // String lock = (String) r.get("lock");
                // if ("true".equals(lock)) {
                // showMessage(ctx, "此项已测过.");
                // } else {
                task.scanResult = selectedScanResult;
                enableNetWork(selectedScanResult);
                // }
            }
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    updateWifi();
                    if (!updated) {
                        updated = true;
                        dismissMessageDialog();
                    }
                    break;
                case MessageWhat.WIFI_SUCESS_CONNECTED:
                   initTask();  
                    ctx.getIntent().putExtra(TAG_REFER_TASK, task);
                    ttw = new Task_Test_Widget(ctx);
                    ctx.setContentView(ttw);
                    dismissMessageDialog();
                    break;

                case MessageWhat.ACCOUNT_INFO_INVALID:
                    showMessage(ctx, "CMCC账号无效，请确认是否配置.");
                    dismissMessageDialog();
                    break;
                case MessageWhat.ACCOUNT_LOGIN_INVALID:
                    showMessage(ctx, "CMCC账号登录失败.");
                    dismissMessageDialog();
                    break;
                case MessageWhat.WIFI_CONNECT_TIMEOUT:
                    connecting = false;
                    dismissMessageDialog();
                    showMessage(ctx, "连接网络超时，请重试.");
                    break;
                case MessageWhat.TASK_BEGIN:
                    doTest();
                    break;
                case MessageWhat.TASK_APINFO_LOADED:
                    showTaskNum();
                    break;
                }
            }
        };
        tm = new TelManager(ctx);
        tm.setHandler(handler);
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        wlanManager.task = task;
        prepare();
    }

    private void prepare() {
        init();
        if (task.selNetType == ConnectivityManager.TYPE_WIFI) {
            this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
            new Thread() {
                public void run() {
                    loadAPInfo();
                    wlanManager.startScan();
                }
            }.start();
        } else {

            Button btn = new Button(ctx);
            btn.setText("开始测试");
            btn.setTextColor(Color.WHITE);
            btn.setBackgroundResource(R.drawable.btn_dblue);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String address = taskAddressText.getText().toString();
                    if (StringUtils.isEmpty(address)) {
                        showMessage(ctx, "请输入当前测试地点.");
                        return;
                    } else {
                        task.taskAddress = address;
                        initTask();
                    }
                }

            });
            taskBtnLayout.addView(btn);
        }
    }

    private void loadAPInfo() {
        String url = GlobalApp.url_ApXML;
        url = url + "?APAddress=" + URLEncoder.encode(task.apName);
        TaskParser parse = new PullTaskParser();
        try {
            InputStream is = HttpUtils.getInputStream(url);
            info = parse.parseAPInfo(is);
            ctx.getIntent().putExtra("info", info.size());
            if (info.size() > 0) {
                wlanManager.apInfo = info;
                wlanManager.filter = true;
                wlanManager.sendMsg(MessageWhat.TASK_APINFO_LOADED);
            }
        } catch (Exception e) {
            Log.e("LoadAP", "加载AP XML文件出错：", e);
        }

    }

    private void showTaskNum() {
        if (info.size() > 0) {
            DBManager db = new DBManager(ctx);
            List<TaskConfig> configs = db.getTask(task.apName, String.valueOf(task.id));
            db.release();
            StringBuffer s = new StringBuffer();
            s.append("当前热点下共有 ").append(info.size()).append(" 项测试，已完成  ")
            	.append(configs.size()).append(" 项.");
            TextView tv = new TextView(ctx);
            tv.setText(s);
            tv.setTextSize(14);
            tv.setTextColor(Color.CYAN);
            detailLayout.addView(tv);
        }
    }

    @Deprecated
    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);

    }

    private void enableNetWork(final ScanResult scan) {
        String address = taskAddressText.getText().toString();
        if (StringUtils.isEmpty(address)) {
            this.showMessage(ctx, "请输入当前测试地点.");
            return;
        }
        task.taskAddress = address;
        this.showMessageDialog(ctx, "正在连接Wifi热点...");
        connecting = true;
        // startConnectTimeoutListener();
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

        // 登录认证
        // DBManager db = new DBManager(ctx);
        // Account account = db.getAccount();
        // if (account == null) {
        // Message m = new Message();
        // m.what = MSG_ACCOUNT_INVALID;
        // hander.sendMessage(m);
        // } else {
        // WebAuthManager wm = new WebAuthManager(ctx);
        // connected = wm.auth("http://www.baidu.com", account.userName,
        // account.password);
        // if (!connected) {
        // Message m = new Message();
        // m.what = MSG_LOGIN_INVALID;
        // hander.sendMessage(m);
        // }
        // }
    }

    private void doTest() {
        dismissMessageDialog();
        task.startTime = StringUtils.getDateTime();
        HttpTestWidgetProxy tw = new HttpTestWidgetProxy(ctx);
        ctx.setContentView(tw);
    }

    private void initTask() {
        this.initTask(task, ctx, task.selNetType);
        ctx.getIntent().putExtra(TAG_REFER_TASK, task);
        wlanManager.sendMsg(MessageWhat.TASK_BEGIN);
    }

    private void updateWifi() {

        List<Map<String, Object>> data = wlanManager.getWifiList();
        //过滤AP根据MAC地址
        //------------------------处理？？
        SimpleAdapter adapter = new SimpleAdapter(ctx, data, R.layout.wifi_list_widget, 
        		new String[] { "ssid", "mac", "img", "level" }, 
        		new int[] {R.id.wifi_ssid, R.id.wifi_mac, R.id.wifi_img, R.id.wifi_level });
        wifiView.setAdapter(adapter);
    }

    private void init() {
        String labelTaskName = this.getResources().getString(R.string.label_task_name);
        String labelApName = this.getResources().getString(R.string.label_apname);
        String labelTaskType = this.getResources().getString(R.string.label_task_type);
        String labelTaskDesc = this.getResources().getString(R.string.label_task_desc);
        String labelTaskRemark = this.getResources().getString(R.string.label_task_remark);
        String labelTaskMan = this.getResources().getString(R.string.label_task_man);
        String labelTaskId = this.getResources().getString(R.string.label_task_id);
        StringBuffer s = new StringBuffer();
        s.append(labelTaskId + " " + task.id).append('\n');
        s.append(labelTaskMan + " " + task.taskMan).append('\n');
        s.append(labelTaskName + " " + task.taskName).append('\n');
        s.append(labelApName + " " + task.apName).append('\n');
        s.append(labelTaskType + " " + task.taskType).append('\n');
        s.append(labelTaskDesc + " " + task.taskDes).append('\n');
        s.append(labelTaskRemark + " " + task.remark);
        TextView tv = new TextView(ctx);
        tv.setTextColor(Color.WHITE);
    //    tv.setText(labelTaskId + task.id);  /// ? ? ?
        tv.setText(s);
        detailLayout.addView(tv);

    }

}
